package handler

import (
	"github.com/DiracLee/dires-go/app/cmdline"
	"github.com/DiracLee/dires-go/app/database"
)

func rollbackFirstKey(db database.DB, args cmdline.CmdLine) []cmdline.CmdLine {
	key := string(args[0])
	return rollbackGivenKeys(db, key)
}

func rollbackGivenKeys(db database.DB, keys ...string) []cmdline.CmdLine {
	var undoCmdLines []cmdline.CmdLine
	for _, key := range keys {
		entity, ok := db.Get(key)
		if !ok {
			undoCmdLines = append(undoCmdLines,
				StringsCommand(cmdline.CmdDel, key),
			)
		} else {
			undoCmdLines = append(undoCmdLines,
				StringsCommand(cmdline.CmdDel, key), // clean existed first
				EntityPayload(key, entity).Args,
				TTLCommand(db, key),
			)
		}
	}
	return undoCmdLines
}

func rollbackHashFields(db database.DB, key string, fields ...string) []cmdline.CmdLine {
	var undoCmdLines []cmdline.CmdLine
	dict, errPayload := db.GetAsDict(key)
	if errPayload != nil {
		return nil
	}
	if dict == nil {
		undoCmdLines = append(undoCmdLines,
			StringsCommand(cmdline.CmdDel, key),
		)
		return undoCmdLines
	}
	for _, field := range fields {
		entity, ok := dict.Get(field)
		if !ok {
			undoCmdLines = append(undoCmdLines,
				StringsCommand(cmdline.CmdHDel, key, field),
			)
		} else {
			value, _ := entity.([]byte)
			undoCmdLines = append(undoCmdLines,
				StringsCommand(cmdline.CmdHSet, key, field, string(value)),
			)
		}
	}
	return undoCmdLines
}
